# -*- coding:utf-8 -*-
import User_Agent_list
import urllib2
import urllib
import random
import json
import codecs
import threading


def down_pic(num):
    global url_name
    headers = dict()
    headers["User-Agent"] = random.choice(User_Agent_list.USER_AGENT_LIST)
    # headers["Cookie"] = ""
    headers["X-Requested-With"] = "XMLHttpRequest"
    headers["Accept"] = "application/json"
    url = "http://huaban.com/search/?" + url_name + "&jbbytamz=&page=" + str(num) + "&per_page=20&wfl=1"
    # "http://huaban.com/search/?q=%E6%AD%A6%E4%BE%A0&jbbytamz=&page=2&per_page=20&wfl=1"

    request = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(request)
    data = response.read()

    # with open('huanban_temp.html', 'wb') as f:
    #     f.write(response.read())
    #     print '页面写入完成'

    if data[:3] == codecs.BOM_UTF8:
        data = data[3:]
    py_object = json.loads(data)
    # py_object = eval(response.read())
    li = []

    for i in py_object['pins']:
        pic_url = "http://img.hb.aicdn.com/" + i['file']['key'].encode('utf-8')
        li.append(pic_url)
    thread = threading.current_thread()
    print thread.getName()

    for j in li:
        request = urllib2.Request(j, headers=headers)
        response = urllib2.urlopen(request)
        s = r'F:\桌面\爬虫temp\%s.jpg' % j[-8:]
        s = s.decode('utf-8').encode('gbk')
        with open(s, 'wb') as f:
            f.write(response.read())
        global p_num, total_num
        p_num += 1
        print '进度%d/%d' % (p_num, total_num)

if __name__ == '__main__':
    p_num = 0
    find_name = raw_input('你要搜索哪类图片：')
    name_dic = {"q": find_name}
    url_name = urllib.urlencode(name_dic)
    num_page = int(raw_input('请输入要获取的页数（每页20张）'))+1
    total_num = (num_page-1) * 20

    for i in range(1, num_page):
        # 单线程
        # down_pic(num_page)

        # 多线程
        t1 = threading.Thread(target=down_pic, args=(i,))
        t1.start()
        print '线程%d创建完毕'%i

